#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <fstream>
#include "utils.hpp"
#include <mutex>

namespace ns_index
{
    struct DocInfo
    {
        std::string title;   // 文档标题
        std::string content; // 文档内容
        std::string url;     // 文档对应url
        uint64_t doc_id;     // 文档id
    };
    struct InvertedElem
    {
        uint64_t doc_id;  // 文档id
        std::string word; // 关键字
        int weight;       // 权重
    };
    typedef std::vector<InvertedElem> InvertedList;
    class Index
    {
    private:
        // 正排索引 文档->key word,下标为文档对应id
        std::vector<DocInfo> forward_index;
        
        // 倒排索引
        std::unordered_map<std::string, InvertedList> inverted_index;

        static Index *instance;
        static std::mutex mtx;

    public:
        Index() {}
        Index(const Index &) = delete;
        Index &operator=(const Index &) = delete;
        ~Index() {}
    public:
        static Index *GetInstance()
        {
            if (nullptr == instance)
            {
                mtx.lock();
                if (nullptr == instance)
                {
                    instance = new Index();
                }
                mtx.unlock();
            }

            return instance;
        }
        // 从文档id找到对应文档内容
        DocInfo *GetForwardIndex(uint64_t doc_id)
        {
            if (doc_id >= forward_index.size())
            {
                std::cerr << "error:doc_id out rage" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }
        // 根据key word，获得倒排索引
        InvertedList *GetInvertedList(const std::string &word)
        {
            auto iter = inverted_index.find(word);
            if (inverted_index.end() == iter)
            {
                std::cerr << "no key word" << std::endl;
                return nullptr;
            }
            return &(iter->second);
        }
        bool BuildIndex(const std::string &input)
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open())
            {
                std::cerr << "open " << input << " error" << std::endl;
                return false;
            }

            std::string line;
            int count = 0;
            while (std::getline(in, line))
            {
                DocInfo *doc = BuildForwardIndex(line);
                if (nullptr == doc)
                {
                    std::cerr << "build " << line << " error" << std::endl;
                    continue;
                }
                BuildInvertedIndex(*doc);
                count++;
                if(count % 50 == 0)
                {
                    std::cout << "已完成" << count << "个索引" << std::endl;
                }
            }
            return true;
        }
        DocInfo *BuildForwardIndex(const std::string &line)
        {
            // 1、解析line，字符串划分
            std::vector<std::string> results;
            const std::string sep = "\3";
            ns_util::StringUtil::Split(line, &results, sep);
            // 2、字符串填充到Doc
            if (results.size() != 3)
            {
                return nullptr;
            }
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size();
            // 3、插入到正排索引的vector
            forward_index.push_back(doc);
            return &forward_index.back();
        }
        bool BuildInvertedIndex(const DocInfo &doc)
        {
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;

                word_cnt() : title_cnt(0), content_cnt(0) {}
            };

            std::unordered_map<std::string, word_cnt> word_map;
            // 对标题进行分词
            std::vector<std::string> title_words;
            ns_util::jiebaUtil::CutString(doc.title, &title_words);
            // 对标题进行词频统计
            for (auto &e : title_words)
            {
                boost::to_lower(e); //统一转化为小写，防止大小写统计有误
                word_map[e].title_cnt++;
            }
            // 对内容进行分词
            std::vector<std::string> content_words;
            ns_util::jiebaUtil::CutString(doc.content, &content_words);
            // 对内容进行词频分析
            for (auto &e : content_words)
            {
                boost::to_lower(e); //统一转化为小写，防止大小写统计有误
                word_map[e].content_cnt++;
            }
            // 插入倒排索引
#define X 10
#define Y 1
            for (auto &word_pair : word_map)
            {
                // 创建一个倒排对象
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                // 建立相关性，即对应关键字权重
                item.weight = X * word_pair.second.title_cnt + Y * word_pair.second.content_cnt;
                // 倒排索引inverted_index是一个unordered_map，
                // inverted_list为对inverted_index[word_pair.first]取引用，
                // 即对vector<InvertedElem>取引用，push_back该文档含对应关键字的倒排对象
                InvertedList &inverted_list = inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }
            return true;
        }
    };
    Index *Index::instance = nullptr;
    std::mutex Index::mtx;
}
